package com.bearhy.jqadmin.service;

import com.bearhy.jqadmin.common.MenuModel;
import com.bearhy.jqadmin.mapper.SysMenuMapper;
import com.bearhy.jqadmin.model.SysMenu;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class SysMenuService {

    @Autowired
    private SysMenuMapper sysMenuMapper;

    /**
     * 获取权限字符串列表
     * @return
     */
    public List<SysMenu> getMenuPermissions(){
        List<SysMenu> menuList = sysMenuMapper.selectAllNotDisabled();
        return menuList;
    }
    /**
     * 获取权限字符串列表
     * @param roleMenuIds
     * @return
     */
    public List<SysMenu> getMenuPermissions(String roleMenuIds){
        String[] menuIds = roleMenuIds.split(",");
        List<SysMenu> menuList = sysMenuMapper.selectNotDisabledByRoleMenuIds(menuIds);
        return menuList;
    }
    /**
     *  根据权限查询出菜单列表
     * @param roleMenuIds
     * @return
     */
    public List<MenuModel> getMenus(String roleMenuIds){
        String[] menuIds = roleMenuIds.split(",");
        List<SysMenu> menuList = sysMenuMapper.selectByRoleMenuIds(menuIds);
        List<MenuModel> trees = new ArrayList<>();
        for (SysMenu m : menuList){
            MenuModel menuModel = new MenuModel();
            //判断这个菜单有几层
            int menuCount = m.getMenuPids().split("/").length;
            //第一层
            if(menuCount == 1){
                menuModel.setId(m.getMenuId());
                menuModel.setName(m.getMenuName());
                menuModel.setIconfont(m.getMenuIcon());
                //获取节点
                menuModel.setSub(getChildrenNode(menuList,m.getMenuId(),2));
                trees.add(menuModel);
            }
        }
        return trees;
    }

    private List<MenuModel> getChildrenNode(List<SysMenu> trees,Integer pId,int chNum){
        List<MenuModel> list = new ArrayList<>();
        for(SysMenu m : trees){
            MenuModel menuModel = new MenuModel();
            if(m.getMenuPids().split("/").length == chNum){
                if(m.getMenuPid().equals(pId)){
                    menuModel.setId(m.getMenuId());
                    menuModel.setName(m.getMenuName());
                    menuModel.setIconfont(m.getMenuIcon());
                    menuModel.setUrl(m.getMenuUrl());
                    menuModel.setSub(getChildrenNode(trees,m.getMenuId(),3));
                    list.add(menuModel);
                }
            }
        }
        return list;
    }
}
